import WtLogger from "./WtLogger";
import {Validator} from 'jsonschema'

class WtPageMemory
{
    constructor(key){
        this.key = key;
    }

    parseJson = (data) => {
        try{
            return JSON.parse(data);
        } catch (e) {
            WtLogger.error('WtPageMemory load failed',e);
            return {};
        }
    };

    load = (schema) => {
        const data = sessionStorage.getItem(this.key);
        const dataObj = this.parseJson(data);

        if(schema){
            const v = new Validator();
            const res = v.validate(dataObj,schema);
            if(!res || res.errors.length){
                this.clear();
                return null;
            }
        }

        return dataObj;

    };

    save = (data) => {
        if(typeof(data) === 'string'){
            sessionStorage.setItem(this.key,data);
        } else if(typeof(data) === 'object'){
            sessionStorage.setItem(this.key,JSON.stringify(data));
        } else {
            WtLogger.error('WtPageMemory save failed of error data type:',data);
        }

    };


    clear = () => {
        sessionStorage.removeItem(this.key);
    }
}

export default WtPageMemory;